package net.cl.db.ds;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.sql.DataSource;

/**
 * 没有连接池的数据源
 * 
 * @author caol64@gmail.com
 */
public class BasicDataSource implements DataSource {

	private String driverClassName;
	private String url;
	private String username;
	private String password;
	private Connection conn;

	public BasicDataSource() {

	}

	public BasicDataSource(String url, String username, String password, String driverClassName) {
		this.url = url;
		this.username = username;
		this.password = password;
		this.driverClassName = driverClassName;
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		try {
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
		}
		if (conn != null && !conn.isClosed())
			return conn;
		if (username == null && password == null)
			conn = DriverManager.getConnection(url);
		else
			conn = DriverManager.getConnection(url, username, password);
		return conn;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return DriverManager.getLogWriter();
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		DriverManager.setLogWriter(out);
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		throw new SQLException("BasicDataSource is not a wrapper.");
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		DriverManager.setLoginTimeout(seconds);
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return DriverManager.getLoginTimeout();
	}

	@Override
	public Connection getConnection() throws SQLException {
		return getConnection(username, password);
	}

	public void close() throws SQLException {
		if (conn != null)
			conn.close();
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrl() {
		return url;
	}

	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}

	public String getDriverClassName() {
		return driverClassName;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
